/**只限于画带速度颜色的轨迹，和清除功能*/

var mp
var lineMap
var canvasLayer
var moveCanvasLayer //轨迹移动的圆点图层
var lineData = []
var drawStarPoint = false
var drawEndPoint = false //默认不画起始坐标点
var drawSpeedLine = true //默认画带速度颜色的轨迹
var getInfoUrl //通过decevid获取公司，车牌等基础信息的url地址入口
var pointCollection //轨迹移动的对象
var options = {
  size: 7,
  shape: 3,
  color: 'rgba(0, 0, 0, 0)'
}
/**
 * 时间格式年：月：日 时：分：秒转成时间戳函数
 * @param date
 * @returns {String}
 */
var changeTime = function changeTime(str) {
  date = str.substring(0, 19)
  var timestamp = new Date(date).getTime()
  return timestamp
}
/**
 * 转成drawTrackLine函数需要的data数组的数据的格式
 * @param（必要） obj：需要划线的数据对象,必要经纬度字段{lng:?,lat:?}或{x:?,y:?},
 * return  changeObj
 */
var changeDrawLineObj = function (obj) {
  if (obj.x || obj.lng) {
    obj.lng = obj.x ? obj.x : obj.lng
    obj.lat = obj.x ? obj.y : obj.lat
  }
  if (obj.loc_time || obj.uploadDate) {
    var loc_time = obj.loc_time ? obj.loc_time : obj.uploadDate
    if (!Number(loc_time)) {
      loc_time = changeTime(loc_time)
    }
    obj.loc_time = loc_time
  }
  if (!obj.lng) {
    return
  }
  return obj
}

/**
 * 画路线执行函数
 * @param1（必要） data：需要划线的数据对象,必要经纬度字段{lng:?,lat:?}或{x:?,y:?},
 * @param2（必要） map：地图map对象
 * @param3     lineStyle{star：bool，end：bool,drawSpeed:bool} ：路线的样式，是否画起始点，速度颜色
 */
function drawTrackLine(data, map, lineStyle) {
  lineData = data //历史数据[经纬度数据]
  mp = null
  mp = map //地图对象
  getInfoUrl = lineStyle.infoUrl ? lineStyle.infoUrl : null //baseURL
  if (lineStyle) {
    lineStyle.star ? (drawStarPoint = true) : (drawStarPoint = false)
    lineStyle.end ? (drawEndPoint = true) : (drawEndPoint = false)
    if (!lineStyle.color) {
      drawSpeedLine = false
    }
  }
  function nullUpdate() {}
  mp.removeOverlay(moveCanvasLayer) //清除图层：轨迹圆点
  moveCanvasLayer = new CanvasLayer({ map: mp, update: nullUpdate, zIndex: 10 })
  mp.addOverlay(moveCanvasLayer) // 添加Overlay
  mp.removeOverlay(canvasLayer)
  canvasLayer = new CanvasLayer({ map: mp, update: drawUpdate }) //绘线
  mp.removeOverlay(pointCollection)
  pointCollection = null
  pointCollection = new BMap.PointCollection(lineData, options) // 初始化PointCollection
  mp.addOverlay(pointCollection) // //移动轨迹  绘画移动的点
  var labelText //地图标注文本
  pointCollection.addEventListener(
    'mouseover',
    function (e) {
      mp.removeOverlay(labelText)
      var opts = {
        position: new BMap.Point(e.point.lng, e.point.lat), // 指定文本标注所在的地理位置
        offset: new BMap.Size(10, -10) //设置文本偏移量
      }
      var textContent =
        '时间:' +
        e.point.uploadDate +
        ', 重量:' +
        common.twoDecimal(e.point.weight) +
        ', 速度:' +
        common.twoDecimal(e.point.speed)
      labelText = new BMap.Label(textContent, opts) // 创建文本标注对象
      labelText.setStyle({
        padding: '5px 288px 22px 5px',
        fontSize: '12px',
        height: '20px',
        lineHeight: '20px',
        border: '1px solid #ccc',
        fontFamily: '微软雅黑'
      })
      mp.addOverlay(labelText)
      var movePoint = {
        lng: e.point.lng,
        lat: e.point.lat
      }
      setMovePoint(movePoint)
    },
    false
  )
  pointCollection.addEventListener(
    'mouseout',
    function (e) {
      mp.removeOverlay(labelText)
      clearMovePoint()
    },
    false
  )
  pointCollection.addEventListener('click', function (e) {
    common.createInfoBox(map, e.point, getInfoUrl)
  })
}
//清除地图上的轨迹路线，
function clearTrackLine(clearMap) {
  clearMap.removeOverlay(canvasLayer)
}
//移动轨迹添加标注点
function setMovePoint(movePoint) {
  if (!movePoint) {
    return
  }
  var moveUpdate = function moveUpdate() {
    var ctx = this.canvas.getContext('2d')
    if (!ctx) {
      return
    }
    var angle = movePoint.course //偏转的角度
    var len = 8 //箭头的长度
    var multiple = 0.5 //距离圆边的距离，半径r的倍数
    var mapPoint = new BMap.Point(movePoint.lng, movePoint.lat)
    var pixel = mp.pointToPixel(mapPoint)
    var point = { x: pixel.x, y: pixel.y } //圆心点坐标
    ctx.beginPath()
    ctx.beginPath()
    ctx.fillStyle = 'rgba(35,152,255,0.1)'
    ctx.lineWidth = 1
    ctx.strokeStyle = '#eee'
    ctx.arc(point.x, point.y, len + 16, 0, 2 * Math.PI)
    ctx.stroke()
    ctx.fill()
    ctx.beginPath()
    ctx.fillStyle = '#5d9aeb'
    ctx.arc(point.x, point.y, len + 2, 0, 2 * Math.PI)
    ctx.fill()
    if (angle) {
      var pointA = {
        x: point.x - multiple * len * Math.cos(((2 * Math.PI) / 360) * (-angle + 30)),
        y: point.y + multiple * len * Math.sin(((2 * Math.PI) / 360) * (-angle + 30))
      }
      var pointO = {
        x: point.x + multiple * len * Math.sin(((2 * Math.PI) / 360) * angle),
        y: point.y - multiple * len * Math.cos(((2 * Math.PI) / 360) * angle)
      }
      var pointB = {
        x: point.x + multiple * len * Math.cos(((2 * Math.PI) / 360) * (-angle - 30)),
        y: point.y - multiple * len * Math.sin(((2 * Math.PI) / 360) * (-angle - 30))
      }
      ctx.beginPath()
      ctx.moveTo(pointA.x, pointA.y)
      ctx.lineCap = 'round'
      ctx.lineWidth = 3
      ctx.strokeStyle = 'white'
      ctx.lineTo(pointO.x, pointO.y)
      ctx.lineTo(pointB.x, pointB.y)
      ctx.stroke()
    } else {
      ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
      ctx.beginPath()
      ctx.strokeStyle = '#c2c2c4'
      ctx.arc(pixel.x, pixel.y, 8, 0, 2 * Math.PI)
      ctx.stroke()
      ctx.beginPath()
      ctx.fillStyle = '#fff'
      ctx.arc(pixel.x, pixel.y, 7, 0, 2 * Math.PI)
      ctx.fill()
      ctx.beginPath()
      ctx.fillStyle = '#1496ff'
      ctx.arc(pixel.x, pixel.y, 2.6, 0, 2 * Math.PI)
      ctx.fill()
    }
  }
  if (typeof moveCanvasLayer != 'undefined') {
    moveCanvasLayer.options.update = moveUpdate
    moveCanvasLayer._draw()
    return
  }
  moveCanvasLayer = new CanvasLayer({
    map: mp,
    update: moveUpdate,
    zIndex: 10
  })
}

/**
 * 清除移动的坐标点（鼠标移动轨迹）
 */
function clearMovePoint() {
  var update = function update() {
    var ctx = this.canvas.getContext('2d')
    if (!ctx) {
      return
    }
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
  }
  if (typeof moveCanvasLayer != 'undefined') {
    moveCanvasLayer.options.update = update
    moveCanvasLayer._draw()
    return
  }
  moveCanvasLayer = new CanvasLayer({
    map: mp,
    update: update,
    zIndex: 10
  })
}

/**
 * 画路线 star， 先画路线，再画箭头标识
 * @param null
 */
function drawUpdate() {
  if (lineData.length < 1) {
    return
  }
  var data = lineData
  var nextArray = []

  var fristTime = 0
  if (data[0]) {
    fristTime = data[0].loc_time
  }
  var lastTime = 0
  if (data[data.length - 1]) {
    lastTime = data[data.length - 1].loc_time
  }
  //var timeDistance=(lastTime-fristTime)/data.length;//取平均时间差
  //	    var timeDistance=10000;//设置时差 10秒内;
  //	    var _time1=0;
  //	    if(data[1]&&data[0]){
  //	    	_time1=data[1].loc_time-data[0].loc_time;
  //	    }
  //	    if(data[2]){
  //	    	var _time2=data[2].loc_time-data[1].loc_time;
  //		    if(_time1==_time2){
  //		    	timeDistance=_time1
  //		    }
  //	    }
  //
  var ctx = this.canvas.getContext('2d')
  if (!ctx) {
    return
  }
  // 清空 canvas
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)

  if (data.length !== 0) {
    var lines = 1
    var lineObj = {}
    var pixelPart = 0
    var pixelPartUnit = 40

    let breakPoint = null

    for (var _i2 = 0, len = data.length; _i2 < len - 1; _i2 = _i2 + 1) {
      let startPoint = data[_i2]
      let endPoint = data[_i2 + 1]
      /**绘画路线star*/
      // 如果出现没有值的点，保存结束位置的点信息
      if (!breakPoint && !endPoint) {
        breakPoint = startPoint
      }
      // 当又出现数据时候获取上次保存的信息
      if (breakPoint && endPoint) {
        startPoint = breakPoint
        breakPoint = null
      }
      // 没有数据不用画
      if (breakPoint) {
        continue
      }
      var bmapPoint = new BMap.Point(startPoint.lng, startPoint.lat)
      var nextBmapPoint = new BMap.Point(endPoint.lng, endPoint.lat)
      var pixel = mp.pointToPixel(bmapPoint)
      var nextPixel = mp.pointToPixel(nextBmapPoint)
      if (pixel && nextPixel) {
        pixelPart = pixelPart + Math.pow(Math.pow(nextPixel.x - pixel.x, 2) + Math.pow(nextPixel.y - pixel.y, 2), 0.5)
        ctx.beginPath()
        ctx.moveTo(pixel.x, pixel.y)
        ctx.lineCap = 'round'
        ctx.lineWidth = 3
        if (startPoint.speed && drawSpeedLine) {
          ctx.strokeStyle = getColorBySpeed(startPoint.speed)
        } else {
          ctx.strokeStyle = 'red'
        }
        ctx.lineTo(nextPixel.x, nextPixel.y) //所有第一次画线的坐标点；
        ctx.stroke()

        /**end*/
        /**绘画路线箭头标识star*/
        if (pixelPart <= pixelPartUnit) {
          continue
        }
        pixelPart = 0
        ctx.beginPath()
        //              if (endPoint.loc_time - data[_i2].loc_time <= timeDistance) {

        // 箭头一共需要5个点：起点、终点、中心点、箭头端点1、箭头端点2

        var midPixel = new BMap.Pixel((pixel.x + nextPixel.x) / 2, (pixel.y + nextPixel.y) / 2)

        // 起点终点距离
        var distance = Math.pow(Math.pow(nextPixel.x - pixel.x, 2) + Math.pow(nextPixel.y - pixel.y, 2), 0.5)
        // 箭头长度
        var pointerLong = 3
        var aPixel = {}
        var bPixel = {}
        if (nextPixel.x - pixel.x === 0) {
          if (nextPixel.y - pixel.y > 0) {
            aPixel.x = midPixel.x - pointerLong * Math.pow(0.5, 0.5)
            aPixel.y = midPixel.y - pointerLong * Math.pow(0.5, 0.5)
            bPixel.x = midPixel.x + pointerLong * Math.pow(0.5, 0.5)
            bPixel.y = midPixel.y - pointerLong * Math.pow(0.5, 0.5)
          } else if (nextPixel.y - pixel.y < 0) {
            aPixel.x = midPixel.x - pointerLong * Math.pow(0.5, 0.5)
            aPixel.y = midPixel.y + pointerLong * Math.pow(0.5, 0.5)
            bPixel.x = midPixel.x + pointerLong * Math.pow(0.5, 0.5)
            bPixel.y = midPixel.y + pointerLong * Math.pow(0.5, 0.5)
          } else {
            continue
          }
        } else {
          var k0 =
            (-Math.pow(2, 0.5) * distance * pointerLong + 2 * (nextPixel.y - pixel.y) * midPixel.y) /
              (2 * (nextPixel.x - pixel.x)) +
            midPixel.x
          var k1 = -((nextPixel.y - pixel.y) / (nextPixel.x - pixel.x))
          var a = Math.pow(k1, 2) + 1
          var b = 2 * k1 * (k0 - midPixel.x) - 2 * midPixel.y
          var c = Math.pow(k0 - midPixel.x, 2) + Math.pow(midPixel.y, 2) - Math.pow(pointerLong, 2)

          aPixel.y = (-b + Math.pow(b * b - 4 * a * c, 0.5)) / (2 * a)
          bPixel.y = (-b - Math.pow(b * b - 4 * a * c, 0.5)) / (2 * a)
          aPixel.x = k1 * aPixel.y + k0
          bPixel.x = k1 * bPixel.y + k0
        }
        ctx.moveTo(aPixel.x, aPixel.y)
        ctx.lineWidth = 2
        ctx.strokeStyle = 'white'
        ctx.lineTo(midPixel.x, midPixel.y)
        ctx.lineTo(bPixel.x, bPixel.y)
        ctx.lineCap = 'round'
      }

      if (startPoint.loc_time >= fristTime && endPoint.loc_time <= lastTime) {
        ctx.stroke()
      }
      //              }
    }
  }

  //          if(drawEndPoint){
  //        	var endImg = new Image();//终点图标
  ////		      	endImg.src = '/resources/js/customer/track/static/images/endpoint.png';
  //        	endImg.src = '/resources/images/car/car01.png';
  //		      	var endPixel = mp.pointToPixel(data[data.length-1]);//终点位置
  //		      	ctx.moveTo(endPixel.x,endPixel.y);
  //		      	ctx.drawImage(endImg,(endPixel.x-15),(endPixel.y-10));
  //        }
  if (drawStarPoint) {
    var starImg = new Image() //起点图标
    starImg.src = 'assets/img/trackImage/startMarker.png'
    for (let i = 0; i < data.length; i++) {
      const item = data[i]
      if (item) {
        var starPoint = new BMap.Point(item.lng, item.lat)
        var starPixel = mp.pointToPixel(starPoint) //起点位置
        ctx.moveTo(starPixel.x, starPixel.y)
        ctx.drawImage(starImg, starPixel.x - 8, starPixel.y - 30)
        break
      }
    }
  }
  //终点图标
  if (drawEndPoint) {
    setEndPointDraw(data[data.length - 1])
  }
}

/**
 * 根据速度设置路线的颜色
 * @param speed
 * return corlor str
 */

var getColorBySpeed = function getColorBySpeed(speed) {
  var color = ''
  var type = Number(speed)
  if (type < 100) {
    color = '#4169e1'
  }
  //		else if(type >= 40 && type < 100) {
  //			color = '#8BC34A';
  //		}
  else {
    color = '#ff4500'
  }
  return color
}
//  var getColorBySpeed= function getColorBySpeed(speed){
//      var color = '';
//      var red = 0;
//      var green = 0;
//      var blue = 0;
//      speed = speed > 100 ? 100 : speed;
//      switch (Math.floor(speed / 25)) {
//          case 0:
//          	red = 187;
//	            green = 0;
//	            blue = 0;
//	            break;
//          case 1:
//              speed = speed - 25;
//              red = 187 + Math.ceil((241 - 187) / 25 * speed);
//              green = 0 + Math.ceil((48 - 0) / 25 * speed);
//              blue = 0 + Math.ceil((48 - 0) / 25 * speed);
//              break;
//          case 2:
//              speed = speed - 50;
//              red = 241 + Math.ceil((255 - 241) / 25 * speed);
//              green = 48 + Math.ceil((200 - 48) / 25 * speed);
//              blue = 48 + Math.ceil((0 - 48) / 25 * speed);
//              break;
//          case 3:
//              speed = speed - 75;
//              red = 255 + Math.ceil((22 - 255) / 25 * speed);
//              green = 200 + Math.ceil((191 - 200) / 25 * speed);
//              blue = 0 + Math.ceil((43 - 0) / 25 * speed);
//              break;
//          case 4:
//              red = 22;
//              green = 191;
//              blue = 43;
//              break;
//	        }
//      red = red.toString(16).length === 1 ? '0' + red.toString(16) : red.toString(16);
//      green = green.toString(16).length === 1 ? '0' + green.toString(16) : green.toString(16);
//      blue = blue.toString(16).length === 1 ? '0' + blue.toString(16) : blue.toString(16);
//      color = '#' + red + green + blue;
//      return color;
//  }

var canvasLayerEnd
function setEndPointDraw(data) {
  var update = function update() {
    var ctx = this.canvas.getContext('2d')
    if (!ctx) {
      return
    }
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
    var point = new BMap.Point(data.lng, data.lat)
    var pixel = mp.pointToPixel(point)
    ctx.beginPath()
    ctx.strokeStyle = '#d0d4d7'
    ctx.arc(pixel.x, pixel.y, 35, 0, 2 * Math.PI)
    ctx.stroke()
    ctx.beginPath()
    ctx.fillStyle = 'rgba(35, 152, 255, 0.14)'
    ctx.arc(pixel.x, pixel.y, 34, 0, 2 * Math.PI)
    ctx.fill()
    ctx.beginPath()
    ctx.strokeStyle = '#c2c2c4'
    ctx.arc(pixel.x, pixel.y, 8, 0, 2 * Math.PI)
    ctx.stroke()
    ctx.beginPath()
    ctx.fillStyle = '#fff'
    ctx.arc(pixel.x, pixel.y, 7, 0, 2 * Math.PI)
    ctx.fill()
    ctx.beginPath()
    ctx.fillStyle = '#1496ff'
    ctx.arc(pixel.x, pixel.y, 2.6, 0, 2 * Math.PI)
    ctx.fill()
  }

  mp.removeOverlay(canvasLayerEnd)

  canvasLayerEnd = new CanvasLayer({
    map: mp,
    update: update,
    zIndex: 10
  })
}
//清除终点图标
function clearCanvasLayerEnd(clearMap) {
  clearMap.removeOverlay(canvasLayerEnd)
}
